﻿using Microsoft.AspNetCore.Mvc.Filters;
using Newtonsoft.Json;
using RuYiAdmin.Net.Common.Global;
using RuYiAdmin.Net.Common.Utility;
using RuYiAdmin.Net.Entity.BusinessDTO.SystemManagement;
using RuYiAdmin.Net.Entity.BusinessEntity.SystemManagement;
using RuYiAdmin.Net.Entity.BusinessEnum;
using RuYiAdmin.Net.Repository.Base;
using System;
using System.Linq;

namespace RuYiAdmin.Net.WebApi.AppCode.Filter
{
    /// <summary>
    /// 日志过滤器
    /// </summary>
    [AttributeUsage(AttributeTargets.Method)]
    public class LogAttribute : ActionFilterAttribute
    {
        private OperationType operationType { get; set; }

        public LogAttribute(OperationType operationType)
        {
            this.operationType = operationType;
        }

        public override void OnResultExecuted(ResultExecutedContext context)
        {
            base.OnResultExecuted(context);

            //设置日志开关
            if (!GlobalContext.LogConfig.IsEnabled)
            {
                return;
            }

            var token = context.HttpContext.Request.Headers["token"];

            //获取用户
            var user = RedisUtil.Get<SysUserDTO>(token);

            if (user == null)
            {
                return;
            }

            var log = new SysLog();

            #region 日志信息赋值

            log.UserId = user.Id;
            log.UserName = user.DisplayName;

            log.OrgId = user.OrgId;

            if (log.OrgId.Equals(Guid.Empty))
            {
                log.OrgName = "none";
            }
            else
            {
                log.OrgName = user.OrgName;
            }

            log.System = context.HttpContext.Request.Headers["User-Agent"].FirstOrDefault().ToString().Split('(')[1].Split(')')[0];
            log.Browser = context.HttpContext.Request.Headers["sec-ch-ua"].FirstOrDefault().ToString().Split(';')[3];

            var ip = context.HttpContext.Request.Headers["X-Forwarded-For"].FirstOrDefault();
            if (string.IsNullOrEmpty(ip))
            {
                ip = context.HttpContext.Connection.RemoteIpAddress.ToString();
            }
            log.IP = ip;

            log.OperationType = this.operationType;
            log.RequestUrl = context.HttpContext.Request.Path.Value;
            log.Params = context.HttpContext.Request.QueryString.Value;

            var isFileStream = context.Result.GetType().Equals(typeof(Microsoft.AspNetCore.Mvc.FileStreamResult));
            var isFile = context.Result.GetType().Equals(typeof(Microsoft.AspNetCore.Mvc.FileResult));

            if (!isFileStream && !isFile)
            {
                log.Result = JsonConvert.SerializeObject(((Microsoft.AspNetCore.Mvc.ObjectResult)context.Result).Value);
            }


            //log.OldVaue = "";
            //log.NewValue = "";

            log.IsDel = 0;

            log.Creator = user.Id;
            log.CreateTime = DateTime.Now;

            log.Modifier = user.Id;
            log.ModifyTime = DateTime.Now;

            #endregion

            #region 监控信息入库

            var Repository = new Repository<SysLog>();

            Repository.AsSugarClient().Insertable<SysLog>(log).ExecuteCommand();

            #endregion
        }
    }
}
